<template>
  <div>
    <div v-if="topInputShow">
      <el-form :inline="true" class="demo-form-inline" >
        <el-form-item label="角色名称">
          <el-input v-model="roleName"  size="small"  placeholder="请输入角色名称"></el-input>
        </el-form-item>
        <el-form-item label="权限字符">
          <el-input v-model="roleKey"  size="small" placeholder="请输入权限字符"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-select placeholder="请选择角色状态"  size="small" v-model="roleStatus" clearable>
            <el-option
                v-for="item in dictStatus"
                :key="item.dictValue"
                :label="item.dictLabel"
                :value="item.dictValue">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间">
          <el-date-picker
              size="small"
              style="width: 250px;"
              v-model="timeDate"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd">
<!--              :picker-options="pickerOptions"-->
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button @click="loadRole(1)" size="small" style="background-color: #23C6C8" icon="el-icon-search" type="success">查询
          </el-button>
          <el-button icon="el-icon-refresh" @click="reset" size="small">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-row class="btn">
      <el-button icon="el-icon-plus" type="primary" size="mini" @click="addRole">新增</el-button>
      <el-button icon="el-icon-edit" type="success" @click="update()" size="mini" :disabled="single">修改</el-button>
      <el-button icon="el-icon-delete" @click="deleteRoles" type="danger" size="mini" :disabled="multiple">删除
      </el-button>
      <el-button icon="el-icon-download" @click="outExe" type="warning" size="mini">导出</el-button>
    </el-row>
    <el-row class="btn-circle">
      <el-button icon="el-icon-search" size="mini" circle @click="topInputShows"></el-button>
      <el-button icon="el-icon-refresh" size="mini" circle @click="refresh"></el-button>
    </el-row>
    <el-table
        :data="roles"
        border
        id="tableId"
        style="width: 100%"
        @selection-change="handleSelectionChange">
      <el-table-column
          type="selection"
          width="55">
      </el-table-column>
      <el-table-column
          label="角色ID"
          width="170">
        <template slot-scope="scope">
          <span style="margin-left: 10px">{{ scope.row.roleId }}</span>
        </template>
      </el-table-column>
      <el-table-column
          label="角色名称"
          width="170">
        <template slot-scope="scope">
          <span style="margin-left: 10px">{{ scope.row.roleName }}</span>
        </template>
      </el-table-column>
      <el-table-column
          label="权限字符"
          width="170">
        <template slot-scope="scope">
          <span style="margin-left: 10px">{{ scope.row.roleKey }}</span>
        </template>
      </el-table-column>
      <el-table-column
          label="显示顺序"
          width="170">
        <template slot-scope="scope">
          <span style="margin-left: 10px">{{ scope.row.roleSort }}</span>
        </template>
      </el-table-column>
      <el-table-column
          label="状态"
          width="170">
        <template slot-scope="scope">
          <el-switch
              v-model="scope.row.status"
              active-value="0"
              inactive-value="1"
              @click.native="unpack(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column
          label="创建时间"
          width="180">
        <template slot-scope="scope">
          <span style="margin-left: 10px">{{ scope.row.createTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button icon="el-icon-edit" @click="showRole(scope.row),dialogRoleVisible=true"  type="text">编辑</el-button>
          <el-button icon="el-icon-circle-check" @click="showRoleDept(scope.row),openDataPermission=true" type="text">数据权限</el-button>
          <el-button icon="el-icon-delete" @click="tips(scope.row.roleId)" type="text">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        class="page"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="current"
        :page-sizes="[5,10,15,20]"
        :page-size="size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
    </el-pagination>


    <el-dialog :title="title" :visible.sync="dialogRoleVisible" class="addRoleDialog">
      <el-form label-width="100px" :model="role" :rules="formRules" ref="form">
        <el-form-item label="角色名称" inline prop="roleName">
          <el-input v-model="role.roleName" placeholder="请输入角色名称" autocomplete="off" ></el-input>
        </el-form-item>
        <el-form-item label="权限字符" inline prop="roleKey">
          <el-input v-model="role.roleKey" placeholder="请输入权限字符" ></el-input>
        </el-form-item>
        <el-form-item label="角色顺序" inline prop="roleSort">
          <el-input-number class="num" v-model="role.roleSort" controls-position="right" :min="0" ></el-input-number>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="role.status">
            <el-radio class="radio" label="0">正常</el-radio>
            <el-radio class="radio" label="1">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="菜单权限">
          <div class="check">
            <el-checkbox>展开/折叠</el-checkbox>
            <el-checkbox v-model="checkAll" @change="handleCheckAllChange">全选/全不选</el-checkbox>
            <el-checkbox v-model="fatherAndSonCheckbox" @change="checkFatherAndSon">父子联动</el-checkbox>
          </div>
          <el-tree class="tree-border"
                   :data="menus"
                   show-checkbox
                   node-key="menuId"
                   ref="tree"
                   highlight-current
                   :check-strictly="isFatherAndSon"
                   :props="defaultProps">
          </el-tree>
        </el-form-item>
        <el-form-item label="备注">
          <el-input
              type="textarea"
              :autosize="{ minRows: 2, maxRows: 4}"
              placeholder="请输入内容"
              v-model="role.remark">
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogRoleVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm('form')">确 定</el-button>
      </div>
    </el-dialog>


    <el-dialog title="分配数据权限" :visible.sync="openDataPermission" width="500px" append-to-body>
      <el-form :model="role" label-width="80px">
        <el-form-item label="角色名称">
          <el-input v-model="role.roleName" :disabled="true" />
        </el-form-item>
        <el-form-item label="权限字符">
          <el-input v-model="role.roleKey" :disabled="true" />
        </el-form-item>
        <el-form-item label="权限范围">
          <el-select v-model="role.dataScope" disabled>
            <el-option
                v-for="item in ScopeOfAuthority"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="数据权限" v-show="role.dataScope == 2">
          <el-checkbox >展开/折叠</el-checkbox>
          <el-checkbox >全选/全不选</el-checkbox>
          <el-checkbox >父子联动</el-checkbox>
          <el-tree
              :data="deptList"
              show-checkbox
              default-expand-all
              ref="dept"
              node-key="deptId"
              highlight-current
              :props="defaultDeptProps"
          ></el-tree>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="saveDept">确 定</el-button>
        <el-button @click="openDataPermission = false">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import FileSaver from "file-saver";
import * as XLSX from "xlsx";
export default {
  name: "RoleView",
  data() {
    return {
      topInputShow:true,
      checkAll:false,
      isFatherAndSon:"",            //树状结构的状态
      fatherAndSonCheckbox: false,  //父子联动复选框的状态
      openDataPermission:false,     //分配数据权限
      deptList:null,
      title:"",
      roles: "",     //角色对象
      roleName: "",  //获取角色名称文本框里面的值
      roleKey: "",   //获取权限字符文本框的值
      roleStatus: "", //获取状态的下拉框的值
      timeDate: null,   //获取时间的值
      ids: [],    // 选中数组
      single: true,  // 非单个禁用
      multiple: true,  // 非多个禁用
      menus: null,     //所有权限集合
      id: "",         //角色id
      excelData:[],   //excel的数据
      dictStatus:"",
      status:"",
      roleOne:"",
      defaultDeptProps:{
        children: "childDept",
        label:"deptName",
      },
      defaultProps: {
        children: "children",  //子节点集合
        label: "menuName",    //节点名
        value: "menuId",
      },
      formRules:{
        roleName:[
          {required: true,message: "角色名不能为空",trigger: "blur"},
        ],
        roleKey:[
          {required: true,message: "权限字符不能为空",trigger: "blur"},
        ],
        roleSort:[
          {required: true,message: "角色顺序不能为空",trigger: "blur"},
        ]
      },
      ScopeOfAuthority:[
        {
          value: "1",
          label: "全部数据权限"
        },
        {
          value: "2",
          label: "自定数据权限"
        },
        {
          value: "3",
          label: "本部门数据权限"
        },
        {
          value: "4",
          label: "本部门及以下数据权限"
        }
      ],
      checkList: "",
      current: 1,
      size: 5,
      pages: 0,
      total:0,
      dialogRoleVisible: false,    //默认添加角色的弹框为false
      role: {
        roleId: 0,
        roleName: "",
        roleKey: "",
        roleSort: "",
        dataScope: "",
        menuCheckStrictly: "",
        deptCheckStrictly: "",
        status: "",
        delFlag: "",
        createBy: "",
        createTime: "",
        updateBy: "",
        updateTime: "",
        remark: ""
      },
    }
  },
  methods: {
    loadRole(current) {
      // this.current = current;
      this.axios.get("role-page?current=" + this.current + "&size=" + this.size + "&roleName=" + this.roleName + "&roleKey=" + this.roleKey + "&roleStatus=" + this.roleStatus + "&timeDate=" + this.timeDate)
          .then(res => {
            this.roles = res.data.data.records;
            this.pages = res.data.data.pages;
            this.total = res.data.data.total;
          })
      this.axios.get("sysMenu/tree")
          .then(res => {
            this.menus = res.data.data;
          })
      this.axios.get("dept-tree")
          .then(res => {
            this.deptList = res.data.data;
          })
      let typeName = "sys_normal_disable";
      this.axios.get("/sysDictData/getBySysDictTypeName/" + typeName)
          .then(res => {
            this.dictStatus = res.data.data;
            console.log(this.dictStatus)
          })
    },
    handleSizeChange(size) {
      // this.size = size;
      // this.loadRole();
      this.size = size;
      this.loadRole(this.current);
    },
    handleCurrentChange(val) {
      this.current = val;
      this.loadRole(this.current);
    },
    //点击重置按钮
    reset(){
      this.roleName ="";
      this.roleKey = "" ;
      this.roleStatus="";
      this.timeDate=null ;
      this.$router.go(0);
    },


    //删除判断
    tips(id,delFlagId) {
      this.delFlagId = delFlagId;
      this.id = id;
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$message({
          type: 'success',
          message: '删除成功!',
        });
        // this.deleteRole(id);
        this.updateDelFlagId(id)
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    topInputShows(){
      this.topInputShow= !this.topInputShow;
    },
    refresh(){
      this.$router.go(0)
    },
    //点击添加按钮时，弹出添加框，数据清空
    addRole(){
      this.title = "添加角色信息"
      this.nullRole();
      //   添加默认值
      this.role.roleName="后勤人员"
      this.role.roleKey="wuYe"
      this.role.status="0"
      this.role.remark="负责管理小区的维修工作"
      this.dialogRoleVisible=true;
      this.$refs.tree.setCheckedKeys([]);



    },
    //添加数据权限
    saveDept(){
      this.axios.post("roleDept/",{role:this.role,depts:this.$refs.dept.getCheckedKeys()})
          .then(res => {
            this.$message({
              type: 'success',
              message: '添加成功!',
            });
            this.loadRole(this.current);
          })
      this.openDataPermission = false;
    },
    //显示部门和角色
    showRoleDept(role){
      this.role = JSON.parse(JSON.stringify(role));
      this.role.dataScope = "2";
      this.axios.get("role-dept/" + this.role.roleId)
          .then(res => {
            if(res.data.code == 200){
              this.$refs.dept.setCheckedKeys(res.data.data);
            }
          })
    },
    //编辑显示
    showRole(role){
      this.title = "修改角色信息"
      this.role = JSON.parse(JSON.stringify(role));
      this.axios.get("role-ids/" + this.role.roleId)
          .then(res => {
            if(res.data.code == 200){
              this.$refs.tree.setCheckedKeys(res.data.data);
            }
          })
    },
    //修改删除状态
    updateDelFlagId(id){
      this.axios.put("role/" + id)
          .then(res => {
            if(res.data.code == 200){
              this.loadRole(this.current);
            }
          })
    },
    //删除
    // deleteRole(id) {
    //   this.axios.delete("role/" + id)
    //       .then(res => {
    //         if (res.data.code == 200) {
    //           this.loadRole(this.current);
    //         }
    //       })
    // },
    //复选框的选择、选择一个时修改和删除按钮都显示 、 选择两个的时候只显示删除
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.roleId)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },
    //多选框选择后点击修改
    update(){
      this.axios.get("role/" + this.ids)
          .then(res => {
            console.log(res.data.data);
            this.role = res.data.data;
          })
      this.axios.get("role-ids/" + this.role.roleId)
          .then(res => {
            if(res.data.code == 200){
              this.$refs.tree.setCheckedKeys(res.data.data);
            }
          })
      this.dialogRoleVisible = true;
    },
    //批量删除
    deleteRoles() {
      this.axios.delete("roles/" + this.ids)
          .then(res => {
            if (res.data.code == 200) {
              this.loadRole(this.current);
            }
          })
    },
    //导出excel表格
    outExe(){
      this.$confirm("此操作将导出excel文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
          .then(() => {
            this.excelData = this.deptList; //你要导出的数据list。
            this.exportExcel();
          })
          .catch(() => {});
    },
    exportExcel() {
      //转换成excel时，使用原始的格式
      var xlsxParam = { raw: true };
      let fix = document.querySelector(".el-table__fixed");
      let wb;
      //判断有无fixed定位，如果有的话去掉，后面再加上，不然数据会重复
      if (fix) {
        wb = XLSX.utils.table_to_book(
            document.querySelector("#tableId").removeChild(fix),xlsxParam);
        document.querySelector("#tableId").appendChild(fix);
      } else {
        wb = XLSX.utils.table_to_book(document.querySelector("#tableId"),xlsxParam);
      }
      var wbout = XLSX.write(wb, {
        bookType: "xlsx",
        bookSST: true,
        type: "array",
      });
      try {
        FileSaver.saveAs(new Blob([wbout], { type: "application/octet-stream" }),"导出详情单.xlsx");
      } catch (e) {
        if (typeof console !== "undefined") console.log(e, wbout);
      }
      return wbout;
    },
    //开关的改变状态的方法
    unpack(row) {
      this.roleOne = row;
      let status = row.status == "0" ? "启用" : "禁用";
      this.$confirm('是否要' + "" + status + "" + row.roleName + '角色吗?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$message({
          type: 'success',
          message: status + '成功!',
        });
        this.updateStatus();
      }).catch(() => {
        if(row.status == "0"){
          row.status = "1"
        }else {
          row.status = "0"
        }
      });
    },
    updateStatus(){
      let roleId = this.roleOne.roleId;
      this.axios.put("role-status/" + roleId)
          .then(res => {
            if(res.data.code == 200){
              this.loadRole(this.current);
            }
          })
    },
    // //保存
    // savaRole() {
    //   if(this.role.roleId == 0){
    //     this.axios.post("role/" , {role:this.role ,menuId:this.$refs.tree.getCheckedKeys()})
    //         .then(res => {
    //           if(res.data.code == 200){
    //             this.loadRole(this.current);
    //             this.dialogRoleVisible = false;
    //           }
    //         })
    //   }else {
    //     this.axios.put("role/" , {role:this.role ,menuId:this.$refs.tree.getCheckedKeys()})
    //         .then(res => {
    //           if(res.data.code == 200){
    //             this.loadRole(this.current);
    //             this.dialogRoleVisible = false;
    //           }
    //         })
    //   }
    //   this.nullRole();
    // },
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          if(this.role.roleId == 0){
            this.axios.post("role/" , {role:this.role ,menuId:this.$refs.tree.getCheckedKeys()})
                .then(res => {
                  if(res.data.code == 200){
                    this.loadRole(this.current);
                    this.dialogRoleVisible = false;
                  }else {
                    this.$message({
                      type: 'warning',
                      message:"该角色名重复",
                    });
                  }
                })
          }else {
            this.axios.put("role/" , {role:this.role ,menuId:this.$refs.tree.getCheckedKeys()})
                .then(res => {
                  if(res.data.code == 200){
                    this.loadRole(this.current);
                    this.dialogRoleVisible = false;
                  }
                })
          }
          this.nullRole();
        } else {
          alert('表单校验不通过')
          return false;
        }
      });
    },
    //父子联动复选框change事件
    checkFatherAndSon() {
      if (this.fatherAndSonCheckbox==true){
        this.isFatherAndSon=false
      }else {
        this.isFatherAndSon=true
      }
    },
    //全选/不全选的change事件
    handleCheckAllChange(){
      if(this.checkAll){
        this.$refs.tree.setCheckedNodes(this.menus);

      }else {
        this.$refs.tree.setCheckedKeys([]);
      }
    },
    nullRole(){
      this.role = {
        roleId: 0,
        roleName: "",
        roleKey: "",
        roleSort: "",
        dataScope: "",
        menuCheckStrictly: "",
        deptCheckStrictly: "",
        status: "",
        delFlag: "",
        createBy: "",
        createTime: "",
        updateBy: "",
        updateTime: "",
        remark: ""
      }
    }
  },
  mounted() {
    this.loadRole(1);
  }
}
</script>

<style scoped>
.page {
  float: right;
  margin-top: 30px;
}

.btn {
  float: left;
  margin-bottom: 10px;
}

.btn-circle {
  float: right;
}

.demo-form-inline {
  position: relative;
  left: -145px;
}
.num {
  position: relative;
  left: -300px;
}

.radio {
  position: relative;
  left: -300px;
}
.tree {
  position: relative;
  left: 10px;
  width: 500px;
}
.tree-border {
  border: 1px solid wheat;
  padding: 10px 0 10px 10px;
  width: 400px;
}

.check {
  position: relative;
  left: -220px;
}
</style>